package com.sf.fy.uav.applet.config;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sf.fy.uav.common.awt.JwtUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectBody;

import net.sf.jsqlparser.statement.select.SetOperationList;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.util.List;

/**
 * mybatis拦截器
 *
 * @author 汪彪
 * @date 2023年08月02日
 */
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class SqlStatementInterceptor implements Interceptor {

    @Autowired
    private DatabaseService databaseService;

    private static final String PROJECT_ID = "projectId";

    public static final String PROJECT_ID_DATA_PARAM = "project_id";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

        //跳过插入操作
        if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }

        // 获取到mapper的信息
        String resource = mappedStatement.getResource();
        //判断是否是单表查询
        if (resource.contains(".java")) {
            return handleMybatisPlusSql(resource, invocation, metaObject);
        }

        return invocation.proceed();
    }

    /**
     * 处理单表查询的sql语句
     *
     * @param resource
     * @param invocation
     * @param metaObject
     * @author 汪彪
     * @date 2023/8/7 14:19
     **/
    private Object handleMybatisPlusSql(String resource, Invocation invocation, MetaObject metaObject) throws Exception {
        String substring = resource.substring(0, resource.indexOf("."));
        String replace = substring.replace("/", ".");
        Class<?> mapperClass = Class.forName(replace);
        if (BaseMapper.class.isAssignableFrom(mapperClass)) {
            //父接口是baseMapper，使用的mybatis-plus

            //给sql添加条件
            String originalSql = (String) metaObject.getValue("delegate.boundSql.sql");

            String sql = this.addExtraCondition(originalSql);
            metaObject.setValue("delegate.boundSql.sql", sql);
        } else {
            //父接口不是baseMapper，并非使用的mybatis-plus
            return invocation.proceed();
        }
        return invocation.proceed();
    }

    private String addExtraCondition(String originalSql) {
        String tableName = "";
        if (originalSql.contains(" FROM ")) {
            tableName = originalSql.split("FROM")[1].trim().split(" ")[0];
        } else if (originalSql.startsWith("UPDATE ")) {
            tableName = originalSql.split(" ")[1];
        }

        String userId = JwtUtil.getUserId();
        if (!ObjectUtils.isEmpty(userId) && !ObjectUtils.isEmpty(tableName)) {

            String columnName = "user_id";
            boolean containsColumn = databaseService.tableContainsColumn(tableName, columnName);
            if (containsColumn) {
                String[] strings = originalSql.split(" WHERE ");
                if (strings.length > 1) {
                    if (strings[1].contains("receiver_tel = ?") && tableName.equals("order_info")) {
                        return originalSql;
                    }
                    if (strings[1].contains("id=?")) {
                        return originalSql;
                    }
                    if (tableName.equals("task_status_log") || tableName.equals("user_wallet")) {
                        return originalSql;
                    }
                }
                return strings[0] + " WHERE user_id = '" + userId + "' AND " + strings[1];
            }

            return originalSql;

        } else {
            return originalSql;
        }

    }


    /**
     * 处理sql语句
     *
     * @param originalSql
     * @param key
     * @param value
     * @date 2023/8/7 14:17
     **/
    private String handleSql(String originalSql, String key, String value) throws JSQLParserException {
        CCJSqlParserManager parserManager = new CCJSqlParserManager();
        //处理select语句
        Select select = (Select) parserManager.parse(new StringReader(originalSql));
        SelectBody selectBody = select.getSelectBody();
        if (selectBody instanceof PlainSelect) {
            this.setWhere((PlainSelect) selectBody, key, value);
        } else if (selectBody instanceof SetOperationList) {
            SetOperationList setOperationList = (SetOperationList) selectBody;
            List<SelectBody> selectBodyList = setOperationList.getSelects();
            selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, key, value));
        }
        return select.toString();
    }

    /**
     * 处理查询条件
     *
     * @param plainSelect
     * @param key
     * @param value
     * @date 2023/8/7 14:16
     **/
    @SneakyThrows(Exception.class)
    protected void setWhere(PlainSelect plainSelect, String key, String value) {
        Table fromItem = (Table) plainSelect.getFromItem();
        // 有别名用别名，无别名用表名，防止字段冲突报错
        Alias fromItemAlias = fromItem.getAlias();
        String mainTableName = fromItemAlias == null ? fromItem.getName() : fromItemAlias.getName();
        // 构建子查询 -- 数据权限过滤SQL
        String dataPermissionSql = "";

        EqualsTo selfEqualsTo = new EqualsTo();
        selfEqualsTo.setLeftExpression(new Column(mainTableName + "." + key));
        selfEqualsTo.setRightExpression(new StringValue(value));
        dataPermissionSql = selfEqualsTo.toString();

        //添加where语句
        if (plainSelect.getWhere() == null) {
            plainSelect.setWhere(CCJSqlParserUtil.parseCondExpression(dataPermissionSql));
        } else {
            plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), CCJSqlParserUtil.parseCondExpression(dataPermissionSql)));
        }
    }
}

